import $http from '@/api'
import * as types from '../mutation-types'

// initial state
const state = {
  all: {},
  cur: {}
}

// getters
const getters = {
  getDetailData: state => {
    return state.cur
  }
}

// actions
const actions = {
  clearDetaiData({ commit, state }) {
    commit(types.DEL_CURRENT_DETAIL)
  },
  getDetailData ({ commit, state }, id) {
    if (state.all[id]) {
      let res = state.all[id]
      commit(types.RECEIVE_DETAIL, { res, id })
      return res
    }
    return $http.getDetail(id)
      .then(res => {
        commit(types.RECEIVE_DETAIL, { res, id })
        return res
      })
      .catch(err => {
        console.log(err)
      })
  }
}

// mutations
const mutations = {
  [types.RECEIVE_DETAIL](state, { res, id }) {
    if (id !== undefined) {
      state.all[id] = res
      state.cur = res
    }
  },
  [types.DEL_CURRENT_DETAIL](state) {
      state.cur = {}
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
